<?php
//+---------------------------------------------------------------------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+---------------------------------------------------------------------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+---------------------------------------------------------------------------------------------------------------------
//| 
//+---------------------------------------------------------------------------------------------------------------------


namespace app\common\event;


use app\admin\model\Log;
use app\admin\model\Menu;
use think\facade\Db;

/**
 * 后台记录访问日志事件
 * @package app\common\event
 */
class AdminLogEvent
{
	public function handle(){
		$this->write();
	}
	protected function write(){
		$menuName = Menu::where('controller',request()->controller())->where('action',lcfirst(request()->action()))->value('name');
		$where = $data = [
			'controller' => request()->controller(),
			'action' => lcfirst(request()->action()),
			'method' => request()->method(),
			'query' => http_build_query(request()->param()),
			'admin_id' => session('SYSTEM_ID')??0,
		];

		$log = Log::where($data)->findOrEmpty();
		if($log->isEmpty()){
			$data = array_merge($data, [
				'name' => !empty($menuName)?$menuName:'',
				'ip' => request()->ip(),
				'createtime' => time(),
			]);
			Log::create($data);
		}else{
			$log->num = Db::raw('num+1');
			$log->createtime = time();
			$log->save();
		}
	}
}